<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.proxy.ustclug.org/css?family=Proxima Nova, sans-serif:300,300italic,400,400italic,700,700italic|STZhongsong:300,300italic,400,400italic,700,700italic|Proxima Nova:300,300italic,400,400italic,700,700italic|Proxima Nova:300,300italic,400,400italic,700,700italic|Proxima Nova:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="python," />





  <link rel="alternate" href="/atom.xml" title="ChangingFond" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.1" />






<meta name="description" content="Python was created by Guido Van Rossum in the early 90s. It is now one of the most popularlanguages in existence. I fell in love with Python for its syntactic clarity. It’s basicallyexecutable pseudoc">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="分分钟学会Python3">
<meta property="og:url" content="http://blog.fangchengjin.cn/2016/10/28/learn-python3-1min/index.html">
<meta property="og:site_name" content="ChangingFond">
<meta property="og:description" content="Python was created by Guido Van Rossum in the early 90s. It is now one of the most popularlanguages in existence. I fell in love with Python for its syntactic clarity. It’s basicallyexecutable pseudoc">
<meta property="og:updated_time" content="2017-06-12T07:33:25.780Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分分钟学会Python3">
<meta name="twitter:description" content="Python was created by Guido Van Rossum in the early 90s. It is now one of the most popularlanguages in existence. I fell in love with Python for its syntactic clarity. It’s basicallyexecutable pseudoc">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.fangchengjin.cn/2016/10/28/learn-python3-1min/"/>





  <title>分分钟学会Python3 | ChangingFond</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?31ac744f9db1ce649f3ee7a827f4c5e8";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=62498440";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>









  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>
    <a href="https://github.com/ChangingFond"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/a6677b08c955af8400f44c6298f40e7d19cc5b2d/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f677261795f3664366436642e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ChangingFond</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">活着，努力着，并收获着快乐</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-guestbook">
          <a href="/guestbook" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            留言
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://blog.fangchengjin.cn/2016/10/28/learn-python3-1min/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ChangingFond">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.ico">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ChangingFond">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">分分钟学会Python3</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-28T00:00:00+08:00">
                2016-10-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/编程笔记/" itemprop="url" rel="index">
                    <span itemprop="name">编程笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2016/10/28/learn-python3-1min/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2016/10/28/learn-python3-1min/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye"> 热度</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>℃
            </span>
          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular<br>languages in existence. I fell in love with Python for its syntactic clarity. It’s basically<br>executable pseudocode.</p>
<p>Feedback would be highly appreciated! You can reach me at <a href="http://twitter.com/louiedinh" target="_blank" rel="external">@louiedinh</a> or louiedinh [at] [google’s email service]</p>
<p>Note: This article applies to Python 3 specifically. Check out <a href="http://learnxinyminutes.com/docs/python/" target="_blank" rel="external">here</a> if you want to learn the old Python 2.7</p>
<a id="more"></a>
<hr>
<p>语言: python3<br>贡献者:  </p>
<pre><code>- [&quot;Louie Dinh&quot;, &quot;http://pythonpracticeprojects.com&quot;]  
- [&quot;Steven Basart&quot;, &quot;http://github.com/xksteven&quot;]  
- [&quot;Andre Polykanine&quot;, &quot;https://github.com/Oire&quot;]  
- [&quot;Zachary Ferguson&quot;, &quot;http://github.com/zfergus2&quot;]  
- [&quot;evuez&quot;, &quot;http://github.com/evuez&quot;]  
</code></pre><p>filename: learnpython3.py<br>译者:  </p>
<pre><code>- [&quot;ChangingFond&quot;, &quot;http://blog.fangchengjin.cn&quot;]
</code></pre><hr>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div><div class="line">155</div><div class="line">156</div><div class="line">157</div><div class="line">158</div><div class="line">159</div><div class="line">160</div><div class="line">161</div><div class="line">162</div><div class="line">163</div><div class="line">164</div><div class="line">165</div><div class="line">166</div><div class="line">167</div><div class="line">168</div><div class="line">169</div><div class="line">170</div><div class="line">171</div><div class="line">172</div><div class="line">173</div><div class="line">174</div><div class="line">175</div><div class="line">176</div><div class="line">177</div><div class="line">178</div><div class="line">179</div><div class="line">180</div><div class="line">181</div><div class="line">182</div><div class="line">183</div><div class="line">184</div><div class="line">185</div><div class="line">186</div><div class="line">187</div><div class="line">188</div><div class="line">189</div><div class="line">190</div><div class="line">191</div><div class="line">192</div><div class="line">193</div><div class="line">194</div><div class="line">195</div><div class="line">196</div><div class="line">197</div><div class="line">198</div><div class="line">199</div><div class="line">200</div><div class="line">201</div><div class="line">202</div><div class="line">203</div><div class="line">204</div><div class="line">205</div><div class="line">206</div><div class="line">207</div><div class="line">208</div><div class="line">209</div><div class="line">210</div><div class="line">211</div><div class="line">212</div><div class="line">213</div><div class="line">214</div><div class="line">215</div><div class="line">216</div><div class="line">217</div><div class="line">218</div><div class="line">219</div><div class="line">220</div><div class="line">221</div><div class="line">222</div><div class="line">223</div><div class="line">224</div><div class="line">225</div><div class="line">226</div><div class="line">227</div><div class="line">228</div><div class="line">229</div><div class="line">230</div><div class="line">231</div><div class="line">232</div><div class="line">233</div><div class="line">234</div><div class="line">235</div><div class="line">236</div><div class="line">237</div><div class="line">238</div><div class="line">239</div><div class="line">240</div><div class="line">241</div><div class="line">242</div><div class="line">243</div><div class="line">244</div><div class="line">245</div><div class="line">246</div><div class="line">247</div><div class="line">248</div><div class="line">249</div><div class="line">250</div><div class="line">251</div><div class="line">252</div><div class="line">253</div><div class="line">254</div><div class="line">255</div><div class="line">256</div><div class="line">257</div><div class="line">258</div><div class="line">259</div><div class="line">260</div><div class="line">261</div><div class="line">262</div><div class="line">263</div><div class="line">264</div><div class="line">265</div><div class="line">266</div><div class="line">267</div><div class="line">268</div><div class="line">269</div><div class="line">270</div><div class="line">271</div><div class="line">272</div><div class="line">273</div><div class="line">274</div><div class="line">275</div><div class="line">276</div><div class="line">277</div><div class="line">278</div><div class="line">279</div><div class="line">280</div><div class="line">281</div><div class="line">282</div><div class="line">283</div><div class="line">284</div><div class="line">285</div><div class="line">286</div><div class="line">287</div><div class="line">288</div><div class="line">289</div><div class="line">290</div><div class="line">291</div><div class="line">292</div><div class="line">293</div><div class="line">294</div><div class="line">295</div><div class="line">296</div><div class="line">297</div><div class="line">298</div><div class="line">299</div><div class="line">300</div><div class="line">301</div><div class="line">302</div><div class="line">303</div><div class="line">304</div><div class="line">305</div><div class="line">306</div><div class="line">307</div><div class="line">308</div><div class="line">309</div><div class="line">310</div><div class="line">311</div><div class="line">312</div><div class="line">313</div><div class="line">314</div><div class="line">315</div><div class="line">316</div><div class="line">317</div><div class="line">318</div><div class="line">319</div><div class="line">320</div><div class="line">321</div><div class="line">322</div><div class="line">323</div><div class="line">324</div><div class="line">325</div><div class="line">326</div><div class="line">327</div><div class="line">328</div><div class="line">329</div><div class="line">330</div><div class="line">331</div><div class="line">332</div><div class="line">333</div><div class="line">334</div><div class="line">335</div><div class="line">336</div><div class="line">337</div><div class="line">338</div><div class="line">339</div><div class="line">340</div><div class="line">341</div><div class="line">342</div><div class="line">343</div><div class="line">344</div><div class="line">345</div><div class="line">346</div><div class="line">347</div><div class="line">348</div><div class="line">349</div><div class="line">350</div><div class="line">351</div><div class="line">352</div><div class="line">353</div><div class="line">354</div><div class="line">355</div><div class="line">356</div><div class="line">357</div><div class="line">358</div><div class="line">359</div><div class="line">360</div><div class="line">361</div><div class="line">362</div><div class="line">363</div><div class="line">364</div><div class="line">365</div><div class="line">366</div><div class="line">367</div><div class="line">368</div><div class="line">369</div><div class="line">370</div><div class="line">371</div><div class="line">372</div><div class="line">373</div><div class="line">374</div><div class="line">375</div><div class="line">376</div><div class="line">377</div><div class="line">378</div><div class="line">379</div><div class="line">380</div><div class="line">381</div><div class="line">382</div><div class="line">383</div><div class="line">384</div><div class="line">385</div><div class="line">386</div><div class="line">387</div><div class="line">388</div><div class="line">389</div><div class="line">390</div><div class="line">391</div><div class="line">392</div><div class="line">393</div><div class="line">394</div><div class="line">395</div><div class="line">396</div><div class="line">397</div><div class="line">398</div><div class="line">399</div><div class="line">400</div><div class="line">401</div><div class="line">402</div><div class="line">403</div><div class="line">404</div><div class="line">405</div><div class="line">406</div><div class="line">407</div><div class="line">408</div><div class="line">409</div><div class="line">410</div><div class="line">411</div><div class="line">412</div><div class="line">413</div><div class="line">414</div><div class="line">415</div><div class="line">416</div><div class="line">417</div><div class="line">418</div><div class="line">419</div><div class="line">420</div><div class="line">421</div><div class="line">422</div><div class="line">423</div><div class="line">424</div><div class="line">425</div><div class="line">426</div><div class="line">427</div><div class="line">428</div><div class="line">429</div><div class="line">430</div><div class="line">431</div><div class="line">432</div><div class="line">433</div><div class="line">434</div><div class="line">435</div><div class="line">436</div><div class="line">437</div><div class="line">438</div><div class="line">439</div><div class="line">440</div><div class="line">441</div><div class="line">442</div><div class="line">443</div><div class="line">444</div><div class="line">445</div><div class="line">446</div><div class="line">447</div><div class="line">448</div><div class="line">449</div><div class="line">450</div><div class="line">451</div><div class="line">452</div><div class="line">453</div><div class="line">454</div><div class="line">455</div><div class="line">456</div><div class="line">457</div><div class="line">458</div><div class="line">459</div><div class="line">460</div><div class="line">461</div><div class="line">462</div><div class="line">463</div><div class="line">464</div><div class="line">465</div><div class="line">466</div><div class="line">467</div><div class="line">468</div><div class="line">469</div><div class="line">470</div><div class="line">471</div><div class="line">472</div><div class="line">473</div><div class="line">474</div><div class="line">475</div><div class="line">476</div><div class="line">477</div><div class="line">478</div><div class="line">479</div><div class="line">480</div><div class="line">481</div><div class="line">482</div><div class="line">483</div><div class="line">484</div><div class="line">485</div><div class="line">486</div><div class="line">487</div><div class="line">488</div><div class="line">489</div><div class="line">490</div><div class="line">491</div><div class="line">492</div><div class="line">493</div><div class="line">494</div><div class="line">495</div><div class="line">496</div><div class="line">497</div><div class="line">498</div><div class="line">499</div><div class="line">500</div><div class="line">501</div><div class="line">502</div><div class="line">503</div><div class="line">504</div><div class="line">505</div><div class="line">506</div><div class="line">507</div><div class="line">508</div><div class="line">509</div><div class="line">510</div><div class="line">511</div><div class="line">512</div><div class="line">513</div><div class="line">514</div><div class="line">515</div><div class="line">516</div><div class="line">517</div><div class="line">518</div><div class="line">519</div><div class="line">520</div><div class="line">521</div><div class="line">522</div><div class="line">523</div><div class="line">524</div><div class="line">525</div><div class="line">526</div><div class="line">527</div><div class="line">528</div><div class="line">529</div><div class="line">530</div><div class="line">531</div><div class="line">532</div><div class="line">533</div><div class="line">534</div><div class="line">535</div><div class="line">536</div><div class="line">537</div><div class="line">538</div><div class="line">539</div><div class="line">540</div><div class="line">541</div><div class="line">542</div><div class="line">543</div><div class="line">544</div><div class="line">545</div><div class="line">546</div><div class="line">547</div><div class="line">548</div><div class="line">549</div><div class="line">550</div><div class="line">551</div><div class="line">552</div><div class="line">553</div><div class="line">554</div><div class="line">555</div><div class="line">556</div><div class="line">557</div><div class="line">558</div><div class="line">559</div><div class="line">560</div><div class="line">561</div><div class="line">562</div><div class="line">563</div><div class="line">564</div><div class="line">565</div><div class="line">566</div><div class="line">567</div><div class="line">568</div><div class="line">569</div><div class="line">570</div><div class="line">571</div><div class="line">572</div><div class="line">573</div><div class="line">574</div><div class="line">575</div><div class="line">576</div><div class="line">577</div><div class="line">578</div><div class="line">579</div><div class="line">580</div><div class="line">581</div><div class="line">582</div><div class="line">583</div><div class="line">584</div><div class="line">585</div><div class="line">586</div><div class="line">587</div><div class="line">588</div><div class="line">589</div><div class="line">590</div><div class="line">591</div><div class="line">592</div><div class="line">593</div><div class="line">594</div><div class="line">595</div><div class="line">596</div><div class="line">597</div><div class="line">598</div><div class="line">599</div><div class="line">600</div><div class="line">601</div><div class="line">602</div><div class="line">603</div><div class="line">604</div><div class="line">605</div><div class="line">606</div><div class="line">607</div><div class="line">608</div><div class="line">609</div><div class="line">610</div><div class="line">611</div><div class="line">612</div><div class="line">613</div><div class="line">614</div><div class="line">615</div><div class="line">616</div><div class="line">617</div><div class="line">618</div><div class="line">619</div><div class="line">620</div><div class="line">621</div><div class="line">622</div><div class="line">623</div><div class="line">624</div><div class="line">625</div><div class="line">626</div><div class="line">627</div><div class="line">628</div><div class="line">629</div><div class="line">630</div><div class="line">631</div><div class="line">632</div><div class="line">633</div><div class="line">634</div><div class="line">635</div><div class="line">636</div><div class="line">637</div><div class="line">638</div><div class="line">639</div><div class="line">640</div><div class="line">641</div><div class="line">642</div><div class="line">643</div><div class="line">644</div><div class="line">645</div><div class="line">646</div><div class="line">647</div><div class="line">648</div><div class="line">649</div><div class="line">650</div><div class="line">651</div><div class="line">652</div><div class="line">653</div><div class="line">654</div><div class="line">655</div><div class="line">656</div><div class="line">657</div><div class="line">658</div><div class="line">659</div><div class="line">660</div><div class="line">661</div><div class="line">662</div><div class="line">663</div><div class="line">664</div><div class="line">665</div><div class="line">666</div><div class="line">667</div><div class="line">668</div><div class="line">669</div><div class="line">670</div><div class="line">671</div><div class="line">672</div><div class="line">673</div><div class="line">674</div><div class="line">675</div><div class="line">676</div><div class="line">677</div><div class="line">678</div><div class="line">679</div><div class="line">680</div><div class="line">681</div><div class="line">682</div><div class="line">683</div><div class="line">684</div><div class="line">685</div><div class="line">686</div><div class="line">687</div><div class="line">688</div><div class="line">689</div><div class="line">690</div><div class="line">691</div><div class="line">692</div><div class="line">693</div><div class="line">694</div><div class="line">695</div><div class="line">696</div><div class="line">697</div><div class="line">698</div><div class="line">699</div><div class="line">700</div><div class="line">701</div><div class="line">702</div><div class="line">703</div><div class="line">704</div><div class="line">705</div><div class="line">706</div><div class="line">707</div><div class="line">708</div><div class="line">709</div><div class="line">710</div><div class="line">711</div><div class="line">712</div><div class="line">713</div><div class="line">714</div><div class="line">715</div><div class="line">716</div><div class="line">717</div><div class="line">718</div><div class="line">719</div><div class="line">720</div><div class="line">721</div><div class="line">722</div><div class="line">723</div><div class="line">724</div><div class="line">725</div><div class="line">726</div><div class="line">727</div><div class="line">728</div><div class="line">729</div><div class="line">730</div><div class="line">731</div><div class="line">732</div><div class="line">733</div><div class="line">734</div><div class="line">735</div><div class="line">736</div><div class="line">737</div><div class="line">738</div><div class="line">739</div><div class="line">740</div><div class="line">741</div><div class="line">742</div><div class="line">743</div><div class="line">744</div><div class="line">745</div><div class="line">746</div><div class="line">747</div><div class="line">748</div><div class="line">749</div><div class="line">750</div><div class="line">751</div><div class="line">752</div><div class="line">753</div><div class="line">754</div><div class="line">755</div><div class="line">756</div><div class="line">757</div><div class="line">758</div><div class="line">759</div><div class="line">760</div><div class="line">761</div><div class="line">762</div><div class="line">763</div><div class="line">764</div><div class="line">765</div><div class="line">766</div><div class="line">767</div><div class="line">768</div><div class="line">769</div><div class="line">770</div><div class="line">771</div><div class="line">772</div><div class="line">773</div><div class="line">774</div><div class="line">775</div><div class="line">776</div><div class="line">777</div><div class="line">778</div><div class="line">779</div><div class="line">780</div><div class="line">781</div><div class="line">782</div><div class="line">783</div><div class="line">784</div><div class="line">785</div><div class="line">786</div><div class="line">787</div><div class="line">788</div><div class="line">789</div><div class="line">790</div><div class="line">791</div><div class="line">792</div><div class="line">793</div><div class="line">794</div><div class="line">795</div><div class="line">796</div><div class="line">797</div><div class="line">798</div><div class="line">799</div><div class="line">800</div><div class="line">801</div><div class="line">802</div><div class="line">803</div><div class="line">804</div><div class="line">805</div><div class="line">806</div><div class="line">807</div><div class="line">808</div><div class="line">809</div><div class="line">810</div><div class="line">811</div><div class="line">812</div><div class="line">813</div><div class="line">814</div><div class="line">815</div><div class="line">816</div><div class="line">817</div><div class="line">818</div><div class="line">819</div><div class="line">820</div><div class="line">821</div><div class="line">822</div><div class="line">823</div><div class="line">824</div><div class="line">825</div><div class="line">826</div><div class="line">827</div><div class="line">828</div><div class="line">829</div><div class="line">830</div><div class="line">831</div><div class="line">832</div><div class="line">833</div><div class="line">834</div><div class="line">835</div><div class="line">836</div><div class="line">837</div><div class="line">838</div><div class="line">839</div><div class="line">840</div><div class="line">841</div><div class="line">842</div><div class="line">843</div><div class="line">844</div><div class="line">845</div><div class="line">846</div><div class="line">847</div><div class="line">848</div><div class="line">849</div><div class="line">850</div><div class="line">851</div><div class="line">852</div><div class="line">853</div><div class="line">854</div><div class="line">855</div><div class="line">856</div><div class="line">857</div><div class="line">858</div><div class="line">859</div><div class="line">860</div><div class="line">861</div><div class="line">862</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment"># Single line comments start with a number symbol.</span></div><div class="line"></div><div class="line"><span class="string">""" Multiline strings can be written</span></div><div class="line">    using three "s, and are often used</div><div class="line">    as comments</div><div class="line">"""</div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 1. Primitive Datatypes and Operators</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># You have numbers</span></div><div class="line"><span class="number">3</span>  <span class="comment"># =&gt; 3</span></div><div class="line"></div><div class="line"><span class="comment"># Math is what you would expect</span></div><div class="line"><span class="number">1</span> + <span class="number">1</span>   <span class="comment"># =&gt; 2</span></div><div class="line"><span class="number">8</span> - <span class="number">1</span>   <span class="comment"># =&gt; 7</span></div><div class="line"><span class="number">10</span> * <span class="number">2</span>  <span class="comment"># =&gt; 20</span></div><div class="line"></div><div class="line"><span class="comment"># Except division which returns floats, real numbers, by default</span></div><div class="line"><span class="number">35</span> / <span class="number">5</span>  <span class="comment"># =&gt; 7.0</span></div><div class="line"></div><div class="line"><span class="comment"># Result of integer division truncated down both for positive and negative.</span></div><div class="line"><span class="number">5</span> // <span class="number">3</span>       <span class="comment"># =&gt; 1</span></div><div class="line"><span class="number">5.0</span> // <span class="number">3.0</span>   <span class="comment"># =&gt; 1.0 # works on floats too</span></div><div class="line"><span class="number">-5</span> // <span class="number">3</span>      <span class="comment"># =&gt; -2</span></div><div class="line"><span class="number">-5.0</span> // <span class="number">3.0</span>  <span class="comment"># =&gt; -2.0</span></div><div class="line"></div><div class="line"><span class="comment"># When you use a float, results are floats</span></div><div class="line"><span class="number">3</span> * <span class="number">2.0</span>  <span class="comment"># =&gt; 6.0</span></div><div class="line"></div><div class="line"><span class="comment"># Modulo operation</span></div><div class="line"><span class="number">7</span> % <span class="number">3</span>  <span class="comment"># =&gt; 1</span></div><div class="line"></div><div class="line"><span class="comment"># Exponentiation (x**y, x to the yth power)</span></div><div class="line"><span class="number">2</span>**<span class="number">4</span>  <span class="comment"># =&gt; 16</span></div><div class="line"></div><div class="line"><span class="comment"># Enforce precedence with parentheses</span></div><div class="line">(<span class="number">1</span> + <span class="number">3</span>) * <span class="number">2</span>  <span class="comment"># =&gt; 8</span></div><div class="line"></div><div class="line"><span class="comment"># Boolean values are primitives (<span class="doctag">Note:</span> the capitalization)</span></div><div class="line"><span class="keyword">True</span></div><div class="line"><span class="keyword">False</span></div><div class="line"></div><div class="line"><span class="comment"># negate with not</span></div><div class="line"><span class="keyword">not</span> <span class="keyword">True</span>   <span class="comment"># =&gt; False</span></div><div class="line"><span class="keyword">not</span> <span class="keyword">False</span>  <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># Boolean Operators</span></div><div class="line"><span class="comment"># Note "and" and "or" are case-sensitive</span></div><div class="line"><span class="keyword">True</span> <span class="keyword">and</span> <span class="keyword">False</span>  <span class="comment"># =&gt; False</span></div><div class="line"><span class="keyword">False</span> <span class="keyword">or</span> <span class="keyword">True</span>   <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># Note using Bool operators with ints</span></div><div class="line"><span class="number">0</span> <span class="keyword">and</span> <span class="number">2</span>     <span class="comment"># =&gt; 0</span></div><div class="line"><span class="number">-5</span> <span class="keyword">or</span> <span class="number">0</span>     <span class="comment"># =&gt; -5</span></div><div class="line"><span class="number">0</span> == <span class="keyword">False</span>  <span class="comment"># =&gt; True</span></div><div class="line"><span class="number">2</span> == <span class="keyword">True</span>   <span class="comment"># =&gt; False</span></div><div class="line"><span class="number">1</span> == <span class="keyword">True</span>   <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># Equality is ==</span></div><div class="line"><span class="number">1</span> == <span class="number">1</span>  <span class="comment"># =&gt; True</span></div><div class="line"><span class="number">2</span> == <span class="number">1</span>  <span class="comment"># =&gt; False</span></div><div class="line"></div><div class="line"><span class="comment"># Inequality is !=</span></div><div class="line"><span class="number">1</span> != <span class="number">1</span>  <span class="comment"># =&gt; False</span></div><div class="line"><span class="number">2</span> != <span class="number">1</span>  <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># More comparisons</span></div><div class="line"><span class="number">1</span> &lt; <span class="number">10</span>  <span class="comment"># =&gt; True</span></div><div class="line"><span class="number">1</span> &gt; <span class="number">10</span>  <span class="comment"># =&gt; False</span></div><div class="line"><span class="number">2</span> &lt;= <span class="number">2</span>  <span class="comment"># =&gt; True</span></div><div class="line"><span class="number">2</span> &gt;= <span class="number">2</span>  <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># Comparisons can be chained!</span></div><div class="line"><span class="number">1</span> &lt; <span class="number">2</span> &lt; <span class="number">3</span>  <span class="comment"># =&gt; True</span></div><div class="line"><span class="number">2</span> &lt; <span class="number">3</span> &lt; <span class="number">2</span>  <span class="comment"># =&gt; False</span></div><div class="line"></div><div class="line"><span class="comment"># (is vs. ==) is checks if two variables refer to the same object, but == checks</span></div><div class="line"><span class="comment"># if the objects pointed to have the same values.</span></div><div class="line">a = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]  <span class="comment"># Point a at a new list, [1, 2, 3, 4]</span></div><div class="line">b = a             <span class="comment"># Point b at what a is pointing to</span></div><div class="line">b <span class="keyword">is</span> a            <span class="comment"># =&gt; True, a and b refer to the same object</span></div><div class="line">b == a            <span class="comment"># =&gt; True, a's and b's objects are equal</span></div><div class="line">b = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]  <span class="comment"># Point b at a new list, [1, 2, 3, 4]</span></div><div class="line">b <span class="keyword">is</span> a            <span class="comment"># =&gt; False, a and b do not refer to the same object</span></div><div class="line">b == a            <span class="comment"># =&gt; True, a's and b's objects are equal</span></div><div class="line"></div><div class="line"><span class="comment"># Strings are created with " or '</span></div><div class="line"><span class="string">"This is a string."</span></div><div class="line"><span class="string">'This is also a string.'</span></div><div class="line"></div><div class="line"><span class="comment"># Strings can be added too! But try not to do this.</span></div><div class="line"><span class="string">"Hello "</span> + <span class="string">"world!"</span>  <span class="comment"># =&gt; "Hello world!"</span></div><div class="line"><span class="comment"># Strings can be added without using '+'</span></div><div class="line"><span class="string">"Hello "</span> <span class="string">"world!"</span>    <span class="comment"># =&gt; "Hello world!"</span></div><div class="line"></div><div class="line"><span class="comment"># A string can be treated like a list of characters</span></div><div class="line"><span class="string">"This is a string"</span>[<span class="number">0</span>]  <span class="comment"># =&gt; 'T'</span></div><div class="line"></div><div class="line"><span class="comment"># You can find the length of a string</span></div><div class="line">len(<span class="string">"This is a string"</span>)  <span class="comment"># =&gt; 16</span></div><div class="line"></div><div class="line"><span class="comment"># .format can be used to format strings, like this:</span></div><div class="line"><span class="string">"&#123;&#125; can be &#123;&#125;"</span>.format(<span class="string">"Strings"</span>, <span class="string">"interpolated"</span>)  <span class="comment"># =&gt; "Strings can be interpolated"</span></div><div class="line"></div><div class="line"><span class="comment"># You can repeat the formatting arguments to save some typing.</span></div><div class="line"><span class="string">"&#123;0&#125; be nimble, &#123;0&#125; be quick, &#123;0&#125; jump over the &#123;1&#125;"</span>.format(<span class="string">"Jack"</span>, <span class="string">"candle stick"</span>)</div><div class="line"><span class="comment"># =&gt; "Jack be nimble, Jack be quick, Jack jump over the candle stick"</span></div><div class="line"></div><div class="line"><span class="comment"># You can use keywords if you don't want to count.</span></div><div class="line"><span class="string">"&#123;name&#125; wants to eat &#123;food&#125;"</span>.format(name=<span class="string">"Bob"</span>, food=<span class="string">"lasagna"</span>)  <span class="comment"># =&gt; "Bob wants to eat lasagna"</span></div><div class="line"></div><div class="line"><span class="comment"># If your Python 3 code also needs to run on Python 2.5 and below, you can also</span></div><div class="line"><span class="comment"># still use the old style of formatting:</span></div><div class="line"><span class="string">"%s can be %s the %s way"</span> % (<span class="string">"Strings"</span>, <span class="string">"interpolated"</span>, <span class="string">"old"</span>)  <span class="comment"># =&gt; "Strings can be interpolated the old way"</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># None is an object</span></div><div class="line"><span class="keyword">None</span>  <span class="comment"># =&gt; None</span></div><div class="line"></div><div class="line"><span class="comment"># Don't use the equality "==" symbol to compare objects to None</span></div><div class="line"><span class="comment"># Use "is" instead. This checks for equality of object identity.</span></div><div class="line"><span class="string">"etc"</span> <span class="keyword">is</span> <span class="keyword">None</span>  <span class="comment"># =&gt; False</span></div><div class="line"><span class="keyword">None</span> <span class="keyword">is</span> <span class="keyword">None</span>   <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># None, 0, and empty strings/lists/dicts all evaluate to False.</span></div><div class="line"><span class="comment"># All other values are True</span></div><div class="line">bool(<span class="number">0</span>)   <span class="comment"># =&gt; False</span></div><div class="line">bool(<span class="string">""</span>)  <span class="comment"># =&gt; False</span></div><div class="line">bool([])  <span class="comment"># =&gt; False</span></div><div class="line">bool(&#123;&#125;)  <span class="comment"># =&gt; False</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 2. Variables and Collections</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># Python has a print function</span></div><div class="line">print(<span class="string">"I'm Python. Nice to meet you!"</span>)  <span class="comment"># =&gt; I'm Python. Nice to meet you!</span></div><div class="line"></div><div class="line"><span class="comment"># By default the print function also prints out a newline at the end.</span></div><div class="line"><span class="comment"># Use the optional argument end to change the end character.</span></div><div class="line">print(<span class="string">"Hello, World"</span>, end=<span class="string">"!"</span>)  <span class="comment"># =&gt; Hello, World!</span></div><div class="line"></div><div class="line"><span class="comment"># Simple way to get input data from console</span></div><div class="line">input_string_var = input(<span class="string">"Enter some data: "</span>) <span class="comment"># Returns the data as a string</span></div><div class="line"><span class="comment"># <span class="doctag">Note:</span> In earlier versions of Python, input() method was named as raw_input()</span></div><div class="line"></div><div class="line"><span class="comment"># No need to declare variables before assigning to them.</span></div><div class="line"><span class="comment"># Convention is to use lower_case_with_underscores</span></div><div class="line">some_var = <span class="number">5</span></div><div class="line">some_var  <span class="comment"># =&gt; 5</span></div><div class="line"></div><div class="line"><span class="comment"># Accessing a previously unassigned variable is an exception.</span></div><div class="line"><span class="comment"># See Control Flow to learn more about exception handling.</span></div><div class="line">some_unknown_var  <span class="comment"># Raises a NameError</span></div><div class="line"></div><div class="line"><span class="comment"># if can be used as an expression</span></div><div class="line"><span class="comment"># Equivalent of C's '?:' ternary operator</span></div><div class="line"><span class="string">"yahoo!"</span> <span class="keyword">if</span> <span class="number">3</span> &gt; <span class="number">2</span> <span class="keyword">else</span> <span class="number">2</span>  <span class="comment"># =&gt; "yahoo!"</span></div><div class="line"></div><div class="line"><span class="comment"># Lists store sequences</span></div><div class="line">li = []</div><div class="line"><span class="comment"># You can start with a prefilled list</span></div><div class="line">other_li = [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</div><div class="line"></div><div class="line"><span class="comment"># Add stuff to the end of a list with append</span></div><div class="line">li.append(<span class="number">1</span>)    <span class="comment"># li is now [1]</span></div><div class="line">li.append(<span class="number">2</span>)    <span class="comment"># li is now [1, 2]</span></div><div class="line">li.append(<span class="number">4</span>)    <span class="comment"># li is now [1, 2, 4]</span></div><div class="line">li.append(<span class="number">3</span>)    <span class="comment"># li is now [1, 2, 4, 3]</span></div><div class="line"><span class="comment"># Remove from the end with pop</span></div><div class="line">li.pop()        <span class="comment"># =&gt; 3 and li is now [1, 2, 4]</span></div><div class="line"><span class="comment"># Let's put it back</span></div><div class="line">li.append(<span class="number">3</span>)    <span class="comment"># li is now [1, 2, 4, 3] again.</span></div><div class="line"></div><div class="line"><span class="comment"># Access a list like you would any array</span></div><div class="line">li[<span class="number">0</span>]   <span class="comment"># =&gt; 1</span></div><div class="line"><span class="comment"># Look at the last element</span></div><div class="line">li[<span class="number">-1</span>]  <span class="comment"># =&gt; 3</span></div><div class="line"></div><div class="line"><span class="comment"># Looking out of bounds is an IndexError</span></div><div class="line">li[<span class="number">4</span>]  <span class="comment"># Raises an IndexError</span></div><div class="line"></div><div class="line"><span class="comment"># You can look at ranges with slice syntax.</span></div><div class="line"><span class="comment"># (It's a closed/open range for you mathy types.)</span></div><div class="line">li[<span class="number">1</span>:<span class="number">3</span>]   <span class="comment"># =&gt; [2, 4]</span></div><div class="line"><span class="comment"># Omit the beginning</span></div><div class="line">li[<span class="number">2</span>:]    <span class="comment"># =&gt; [4, 3]</span></div><div class="line"><span class="comment"># Omit the end</span></div><div class="line">li[:<span class="number">3</span>]    <span class="comment"># =&gt; [1, 2, 4]</span></div><div class="line"><span class="comment"># Select every second entry</span></div><div class="line">li[::<span class="number">2</span>]   <span class="comment"># =&gt;[1, 4]</span></div><div class="line"><span class="comment"># Return a reversed copy of the list</span></div><div class="line">li[::<span class="number">-1</span>]  <span class="comment"># =&gt; [3, 4, 2, 1]</span></div><div class="line"><span class="comment"># Use any combination of these to make advanced slices</span></div><div class="line"><span class="comment"># li[start:end:step]</span></div><div class="line"></div><div class="line"><span class="comment"># Make a one layer deep copy using slices</span></div><div class="line">li2 = li[:]  <span class="comment"># =&gt; li2 = [1, 2, 4, 3] but (li2 is li) will result in false.</span></div><div class="line"></div><div class="line"><span class="comment"># Remove arbitrary elements from a list with "del"</span></div><div class="line"><span class="keyword">del</span> li[<span class="number">2</span>]  <span class="comment"># li is now [1, 2, 3]</span></div><div class="line"></div><div class="line"><span class="comment"># Remove first occurrence of a value</span></div><div class="line">li.remove(<span class="number">2</span>)  <span class="comment"># li is now [1, 3]</span></div><div class="line">li.remove(<span class="number">2</span>)  <span class="comment"># Raises a ValueError as 2 is not in the list</span></div><div class="line"></div><div class="line"><span class="comment"># Insert an element at a specific index</span></div><div class="line">li.insert(<span class="number">1</span>, <span class="number">2</span>)  <span class="comment"># li is now [1, 2, 3] again</span></div><div class="line"></div><div class="line"><span class="comment"># Get the index of the first item found matching the argument</span></div><div class="line">li.index(<span class="number">2</span>)  <span class="comment"># =&gt; 1</span></div><div class="line">li.index(<span class="number">4</span>)  <span class="comment"># Raises a ValueError as 4 is not in the list</span></div><div class="line"></div><div class="line"><span class="comment"># You can add lists</span></div><div class="line"><span class="comment"># <span class="doctag">Note:</span> values for li and for other_li are not modified.</span></div><div class="line">li + other_li  <span class="comment"># =&gt; [1, 2, 3, 4, 5, 6]</span></div><div class="line"></div><div class="line"><span class="comment"># Concatenate lists with "extend()"</span></div><div class="line">li.extend(other_li)  <span class="comment"># Now li is [1, 2, 3, 4, 5, 6]</span></div><div class="line"></div><div class="line"><span class="comment"># Check for existence in a list with "in"</span></div><div class="line"><span class="number">1</span> <span class="keyword">in</span> li  <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># Examine the length with "len()"</span></div><div class="line">len(li)  <span class="comment"># =&gt; 6</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># Tuples are like lists but are immutable.</span></div><div class="line">tup = (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</div><div class="line">tup[<span class="number">0</span>]      <span class="comment"># =&gt; 1</span></div><div class="line">tup[<span class="number">0</span>] = <span class="number">3</span>  <span class="comment"># Raises a TypeError</span></div><div class="line"></div><div class="line"><span class="comment"># Note that a tuple of length one has to have a comma after the last element but</span></div><div class="line"><span class="comment"># tuples of other lengths, even zero, do not.</span></div><div class="line">type((<span class="number">1</span>))   <span class="comment"># =&gt; &lt;class 'int'&gt;</span></div><div class="line">type((<span class="number">1</span>,))  <span class="comment"># =&gt; &lt;class 'tuple'&gt;</span></div><div class="line">type(())    <span class="comment"># =&gt; &lt;class 'tuple'&gt;</span></div><div class="line"></div><div class="line"><span class="comment"># You can do most of the list operations on tuples too</span></div><div class="line">len(tup)         <span class="comment"># =&gt; 3</span></div><div class="line">tup + (<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>)  <span class="comment"># =&gt; (1, 2, 3, 4, 5, 6)</span></div><div class="line">tup[:<span class="number">2</span>]          <span class="comment"># =&gt; (1, 2)</span></div><div class="line"><span class="number">2</span> <span class="keyword">in</span> tup         <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># You can unpack tuples (or lists) into variables</span></div><div class="line">a, b, c = (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)  <span class="comment"># a is now 1, b is now 2 and c is now 3</span></div><div class="line"><span class="comment"># You can also do extended unpacking</span></div><div class="line">a, *b, c = (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)  <span class="comment"># a is now 1, b is now [2, 3] and c is now 4</span></div><div class="line"><span class="comment"># Tuples are created by default if you leave out the parentheses</span></div><div class="line">d, e, f = <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span></div><div class="line"><span class="comment"># Now look how easy it is to swap two values</span></div><div class="line">e, d = d, e  <span class="comment"># d is now 5 and e is now 4</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># Dictionaries store mappings</span></div><div class="line">empty_dict = &#123;&#125;</div><div class="line"><span class="comment"># Here is a prefilled dictionary</span></div><div class="line">filled_dict = &#123;<span class="string">"one"</span>: <span class="number">1</span>, <span class="string">"two"</span>: <span class="number">2</span>, <span class="string">"three"</span>: <span class="number">3</span>&#125;</div><div class="line"></div><div class="line"><span class="comment"># Note keys for dictionaries have to be immutable types. This is to ensure that</span></div><div class="line"><span class="comment"># the key can be converted to a constant hash value for quick look-ups.</span></div><div class="line"><span class="comment"># Immutable types include ints, floats, strings, tuples.</span></div><div class="line">invalid_dict = &#123;[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]: <span class="string">"123"</span>&#125;  <span class="comment"># =&gt; Raises a TypeError: unhashable type: 'list'</span></div><div class="line">valid_dict = &#123;(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>):[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]&#125;   <span class="comment"># Values can be of any type, however.</span></div><div class="line"></div><div class="line"><span class="comment"># Look up values with []</span></div><div class="line">filled_dict[<span class="string">"one"</span>]  <span class="comment"># =&gt; 1</span></div><div class="line"></div><div class="line"><span class="comment"># Get all keys as an iterable with "keys()". We need to wrap the call in list()</span></div><div class="line"><span class="comment"># to turn it into a list. We'll talk about those later.  Note - Dictionary key</span></div><div class="line"><span class="comment"># ordering is not guaranteed. Your results might not match this exactly.</span></div><div class="line">list(filled_dict.keys())  <span class="comment"># =&gt; ["three", "two", "one"]</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># Get all values as an iterable with "values()". Once again we need to wrap it</span></div><div class="line"><span class="comment"># in list() to get it out of the iterable. Note - Same as above regarding key</span></div><div class="line"><span class="comment"># ordering.</span></div><div class="line">list(filled_dict.values())  <span class="comment"># =&gt; [3, 2, 1]</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># Check for existence of keys in a dictionary with "in"</span></div><div class="line"><span class="string">"one"</span> <span class="keyword">in</span> filled_dict  <span class="comment"># =&gt; True</span></div><div class="line"><span class="number">1</span> <span class="keyword">in</span> filled_dict      <span class="comment"># =&gt; False</span></div><div class="line"></div><div class="line"><span class="comment"># Looking up a non-existing key is a KeyError</span></div><div class="line">filled_dict[<span class="string">"four"</span>]  <span class="comment"># KeyError</span></div><div class="line"></div><div class="line"><span class="comment"># Use "get()" method to avoid the KeyError</span></div><div class="line">filled_dict.get(<span class="string">"one"</span>)      <span class="comment"># =&gt; 1</span></div><div class="line">filled_dict.get(<span class="string">"four"</span>)     <span class="comment"># =&gt; None</span></div><div class="line"><span class="comment"># The get method supports a default argument when the value is missing</span></div><div class="line">filled_dict.get(<span class="string">"one"</span>, <span class="number">4</span>)   <span class="comment"># =&gt; 1</span></div><div class="line">filled_dict.get(<span class="string">"four"</span>, <span class="number">4</span>)  <span class="comment"># =&gt; 4</span></div><div class="line"></div><div class="line"><span class="comment"># "setdefault()" inserts into a dictionary only if the given key isn't present</span></div><div class="line">filled_dict.setdefault(<span class="string">"five"</span>, <span class="number">5</span>)  <span class="comment"># filled_dict["five"] is set to 5</span></div><div class="line">filled_dict.setdefault(<span class="string">"five"</span>, <span class="number">6</span>)  <span class="comment"># filled_dict["five"] is still 5</span></div><div class="line"></div><div class="line"><span class="comment"># Adding to a dictionary</span></div><div class="line">filled_dict.update(&#123;<span class="string">"four"</span>:<span class="number">4</span>&#125;)  <span class="comment"># =&gt; &#123;"one": 1, "two": 2, "three": 3, "four": 4&#125;</span></div><div class="line"><span class="comment">#filled_dict["four"] = 4        #another way to add to dict</span></div><div class="line"></div><div class="line"><span class="comment"># Remove keys from a dictionary with del</span></div><div class="line"><span class="keyword">del</span> filled_dict[<span class="string">"one"</span>]  <span class="comment"># Removes the key "one" from filled dict</span></div><div class="line"></div><div class="line"><span class="comment"># From Python 3.5 you can also use the additional unpacking options</span></div><div class="line">&#123;<span class="string">'a'</span>: <span class="number">1</span>, **&#123;<span class="string">'b'</span>: <span class="number">2</span>&#125;&#125;  <span class="comment"># =&gt; &#123;'a': 1, 'b': 2&#125;</span></div><div class="line">&#123;<span class="string">'a'</span>: <span class="number">1</span>, **&#123;<span class="string">'a'</span>: <span class="number">2</span>&#125;&#125;  <span class="comment"># =&gt; &#123;'a': 2&#125;</span></div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># Sets store ... well sets</span></div><div class="line">empty_set = set()</div><div class="line"><span class="comment"># Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.</span></div><div class="line">some_set = &#123;<span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;  <span class="comment"># some_set is now &#123;1, 2, 3, 4&#125;</span></div><div class="line"></div><div class="line"><span class="comment"># Similar to keys of a dictionary, elements of a set have to be immutable.</span></div><div class="line">invalid_set = &#123;[<span class="number">1</span>], <span class="number">1</span>&#125;  <span class="comment"># =&gt; Raises a TypeError: unhashable type: 'list'</span></div><div class="line">valid_set = &#123;(<span class="number">1</span>,), <span class="number">1</span>&#125;</div><div class="line"></div><div class="line"><span class="comment"># Can set new variables to a set</span></div><div class="line">filled_set = some_set</div><div class="line"></div><div class="line"><span class="comment"># Add one more item to the set</span></div><div class="line">filled_set.add(<span class="number">5</span>)  <span class="comment"># filled_set is now &#123;1, 2, 3, 4, 5&#125;</span></div><div class="line"></div><div class="line"><span class="comment"># Do set intersection with &amp;</span></div><div class="line">other_set = &#123;<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>&#125;</div><div class="line">filled_set &amp; other_set  <span class="comment"># =&gt; &#123;3, 4, 5&#125;</span></div><div class="line"></div><div class="line"><span class="comment"># Do set union with |</span></div><div class="line">filled_set | other_set  <span class="comment"># =&gt; &#123;1, 2, 3, 4, 5, 6&#125;</span></div><div class="line"></div><div class="line"><span class="comment"># Do set difference with -</span></div><div class="line">&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125; - &#123;<span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>&#125;  <span class="comment"># =&gt; &#123;1, 4&#125;</span></div><div class="line"></div><div class="line"><span class="comment"># Do set symmetric difference with ^</span></div><div class="line">&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125; ^ &#123;<span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>&#125;  <span class="comment"># =&gt; &#123;1, 4, 5&#125;</span></div><div class="line"></div><div class="line"><span class="comment"># Check if set on the left is a superset of set on the right</span></div><div class="line">&#123;<span class="number">1</span>, <span class="number">2</span>&#125; &gt;= &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125; <span class="comment"># =&gt; False</span></div><div class="line"></div><div class="line"><span class="comment"># Check if set on the left is a subset of set on the right</span></div><div class="line">&#123;<span class="number">1</span>, <span class="number">2</span>&#125; &lt;= &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>&#125; <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># Check for existence in a set with in</span></div><div class="line"><span class="number">2</span> <span class="keyword">in</span> filled_set   <span class="comment"># =&gt; True</span></div><div class="line"><span class="number">10</span> <span class="keyword">in</span> filled_set  <span class="comment"># =&gt; False</span></div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 3. Control Flow and Iterables</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># Let's just make a variable</span></div><div class="line">some_var = <span class="number">5</span></div><div class="line"></div><div class="line"><span class="comment"># Here is an if statement. Indentation is significant in python!</span></div><div class="line"><span class="comment"># prints "some_var is smaller than 10"</span></div><div class="line"><span class="keyword">if</span> some_var &gt; <span class="number">10</span>:</div><div class="line">    print(<span class="string">"some_var is totally bigger than 10."</span>)</div><div class="line"><span class="keyword">elif</span> some_var &lt; <span class="number">10</span>:    <span class="comment"># This elif clause is optional.</span></div><div class="line">    print(<span class="string">"some_var is smaller than 10."</span>)</div><div class="line"><span class="keyword">else</span>:                  <span class="comment"># This is optional too.</span></div><div class="line">    print(<span class="string">"some_var is indeed 10."</span>)</div><div class="line"></div><div class="line"></div><div class="line"><span class="string">"""</span></div><div class="line">For loops iterate over lists</div><div class="line">prints:</div><div class="line">    dog is a mammal</div><div class="line">    cat is a mammal</div><div class="line">    mouse is a mammal</div><div class="line">"""</div><div class="line"><span class="keyword">for</span> animal <span class="keyword">in</span> [<span class="string">"dog"</span>, <span class="string">"cat"</span>, <span class="string">"mouse"</span>]:</div><div class="line">    <span class="comment"># You can use format() to interpolate formatted strings</span></div><div class="line">    print(<span class="string">"&#123;&#125; is a mammal"</span>.format(animal))</div><div class="line"></div><div class="line"><span class="string">"""</span></div><div class="line">"range(number)" returns an iterable of numbers</div><div class="line">from zero to the given number</div><div class="line">prints:</div><div class="line">    0</div><div class="line">    1</div><div class="line">    2</div><div class="line">    3</div><div class="line">"""</div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">4</span>):</div><div class="line">    print(i)</div><div class="line"></div><div class="line"><span class="string">"""</span></div><div class="line">"range(lower, upper)" returns an iterable of numbers</div><div class="line">from the lower number to the upper number</div><div class="line">prints:</div><div class="line">    4</div><div class="line">    5</div><div class="line">    6</div><div class="line">    7</div><div class="line">"""</div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">4</span>, <span class="number">8</span>):</div><div class="line">    print(i)</div><div class="line"></div><div class="line"><span class="string">"""</span></div><div class="line">"range(lower, upper, step)" returns an iterable of numbers</div><div class="line">from the lower number to the upper number, while incrementing</div><div class="line">by step. If step is not indicated, the default value is 1.</div><div class="line">prints:</div><div class="line">    4</div><div class="line">    6</div><div class="line">"""</div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">4</span>, <span class="number">8</span>, <span class="number">2</span>):</div><div class="line">    print(i)</div><div class="line"><span class="string">"""</span></div><div class="line"></div><div class="line">While loops go until a condition is no longer met.</div><div class="line">prints:</div><div class="line">    0</div><div class="line">    1</div><div class="line">    2</div><div class="line">    3</div><div class="line">"""</div><div class="line">x = <span class="number">0</span></div><div class="line"><span class="keyword">while</span> x &lt; <span class="number">4</span>:</div><div class="line">    print(x)</div><div class="line">    x += <span class="number">1</span>  <span class="comment"># Shorthand for x = x + 1</span></div><div class="line"></div><div class="line"><span class="comment"># Handle exceptions with a try/except block</span></div><div class="line"><span class="keyword">try</span>:</div><div class="line">    <span class="comment"># Use "raise" to raise an error</span></div><div class="line">    <span class="keyword">raise</span> IndexError(<span class="string">"This is an index error"</span>)</div><div class="line"><span class="keyword">except</span> IndexError <span class="keyword">as</span> e:</div><div class="line">    <span class="keyword">pass</span>                 <span class="comment"># Pass is just a no-op. Usually you would do recovery here.</span></div><div class="line"><span class="keyword">except</span> (TypeError, NameError):</div><div class="line">    <span class="keyword">pass</span>                 <span class="comment"># Multiple exceptions can be handled together, if required.</span></div><div class="line"><span class="keyword">else</span>:                    <span class="comment"># Optional clause to the try/except block. Must follow all except blocks</span></div><div class="line">    print(<span class="string">"All good!"</span>)   <span class="comment"># Runs only if the code in try raises no exceptions</span></div><div class="line"><span class="keyword">finally</span>:                 <span class="comment">#  Execute under all circumstances</span></div><div class="line">    print(<span class="string">"We can clean up resources here"</span>)</div><div class="line"></div><div class="line"><span class="comment"># Instead of try/finally to cleanup resources you can use a with statement</span></div><div class="line"><span class="keyword">with</span> open(<span class="string">"myfile.txt"</span>) <span class="keyword">as</span> f:</div><div class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> f:</div><div class="line">        print(line)</div><div class="line"></div><div class="line"><span class="comment"># Python offers a fundamental abstraction called the Iterable.</span></div><div class="line"><span class="comment"># An iterable is an object that can be treated as a sequence.</span></div><div class="line"><span class="comment"># The object returned the range function, is an iterable.</span></div><div class="line"></div><div class="line">filled_dict = &#123;<span class="string">"one"</span>: <span class="number">1</span>, <span class="string">"two"</span>: <span class="number">2</span>, <span class="string">"three"</span>: <span class="number">3</span>&#125;</div><div class="line">our_iterable = filled_dict.keys()</div><div class="line">print(our_iterable)  <span class="comment"># =&gt; dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.</span></div><div class="line"></div><div class="line"><span class="comment"># We can loop over it.</span></div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> our_iterable:</div><div class="line">    print(i)  <span class="comment"># Prints one, two, three</span></div><div class="line"></div><div class="line"><span class="comment"># However we cannot address elements by index.</span></div><div class="line">our_iterable[<span class="number">1</span>]  <span class="comment"># Raises a TypeError</span></div><div class="line"></div><div class="line"><span class="comment"># An iterable is an object that knows how to create an iterator.</span></div><div class="line">our_iterator = iter(our_iterable)</div><div class="line"></div><div class="line"><span class="comment"># Our iterator is an object that can remember the state as we traverse through it.</span></div><div class="line"><span class="comment"># We get the next object with "next()".</span></div><div class="line">next(our_iterator)  <span class="comment"># =&gt; "one"</span></div><div class="line"></div><div class="line"><span class="comment"># It maintains state as we iterate.</span></div><div class="line">next(our_iterator)  <span class="comment"># =&gt; "two"</span></div><div class="line">next(our_iterator)  <span class="comment"># =&gt; "three"</span></div><div class="line"></div><div class="line"><span class="comment"># After the iterator has returned all of its data, it gives you a StopIterator Exception</span></div><div class="line">next(our_iterator)  <span class="comment"># Raises StopIteration</span></div><div class="line"></div><div class="line"><span class="comment"># You can grab all the elements of an iterator by calling list() on it.</span></div><div class="line">list(filled_dict.keys())  <span class="comment"># =&gt; Returns ["one", "two", "three"]</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 4. Functions</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># Use "def" to create new functions</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(x, y)</span>:</span></div><div class="line">    print(<span class="string">"x is &#123;&#125; and y is &#123;&#125;"</span>.format(x, y))</div><div class="line">    <span class="keyword">return</span> x + y  <span class="comment"># Return values with a return statement</span></div><div class="line"></div><div class="line"><span class="comment"># Calling functions with parameters</span></div><div class="line">add(<span class="number">5</span>, <span class="number">6</span>)  <span class="comment"># =&gt; prints out "x is 5 and y is 6" and returns 11</span></div><div class="line"></div><div class="line"><span class="comment"># Another way to call functions is with keyword arguments</span></div><div class="line">add(y=<span class="number">6</span>, x=<span class="number">5</span>)  <span class="comment"># Keyword arguments can arrive in any order.</span></div><div class="line"></div><div class="line"><span class="comment"># You can define functions that take a variable number of</span></div><div class="line"><span class="comment"># positional arguments</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">varargs</span><span class="params">(*args)</span>:</span></div><div class="line">    <span class="keyword">return</span> args</div><div class="line"></div><div class="line">varargs(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)  <span class="comment"># =&gt; (1, 2, 3)</span></div><div class="line"></div><div class="line"><span class="comment"># You can define functions that take a variable number of</span></div><div class="line"><span class="comment"># keyword arguments, as well</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">keyword_args</span><span class="params">(**kwargs)</span>:</span></div><div class="line">    <span class="keyword">return</span> kwargs</div><div class="line"></div><div class="line"><span class="comment"># Let's call it to see what happens</span></div><div class="line">keyword_args(big=<span class="string">"foot"</span>, loch=<span class="string">"ness"</span>)  <span class="comment"># =&gt; &#123;"big": "foot", "loch": "ness"&#125;</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># You can do both at once, if you like</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">all_the_args</span><span class="params">(*args, **kwargs)</span>:</span></div><div class="line">    print(args)</div><div class="line">    print(kwargs)</div><div class="line"><span class="string">"""</span></div><div class="line">all_the_args(1, 2, a=3, b=4) prints:</div><div class="line">    (1, 2)</div><div class="line">    &#123;"a": 3, "b": 4&#125;</div><div class="line">"""</div><div class="line"></div><div class="line"><span class="comment"># When calling functions, you can do the opposite of args/kwargs!</span></div><div class="line"><span class="comment"># Use * to expand tuples and use ** to expand kwargs.</span></div><div class="line">args = (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</div><div class="line">kwargs = &#123;<span class="string">"a"</span>: <span class="number">3</span>, <span class="string">"b"</span>: <span class="number">4</span>&#125;</div><div class="line">all_the_args(*args)            <span class="comment"># equivalent to foo(1, 2, 3, 4)</span></div><div class="line">all_the_args(**kwargs)         <span class="comment"># equivalent to foo(a=3, b=4)</span></div><div class="line">all_the_args(*args, **kwargs)  <span class="comment"># equivalent to foo(1, 2, 3, 4, a=3, b=4)</span></div><div class="line"></div><div class="line"><span class="comment"># Returning multiple values (with tuple assignments)</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">swap</span><span class="params">(x, y)</span>:</span></div><div class="line">    <span class="keyword">return</span> y, x  <span class="comment"># Return multiple values as a tuple without the parenthesis.</span></div><div class="line">                 <span class="comment"># (<span class="doctag">Note:</span> parenthesis have been excluded but can be included)</span></div><div class="line"></div><div class="line">x = <span class="number">1</span></div><div class="line">y = <span class="number">2</span></div><div class="line">x, y = swap(x, y)     <span class="comment"># =&gt; x = 2, y = 1</span></div><div class="line"><span class="comment"># (x, y) = swap(x,y)  # Again parenthesis have been excluded but can be included.</span></div><div class="line"></div><div class="line"><span class="comment"># Function Scope</span></div><div class="line">x = <span class="number">5</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">set_x</span><span class="params">(num)</span>:</span></div><div class="line">    <span class="comment"># Local var x not the same as global variable x</span></div><div class="line">    x = num    <span class="comment"># =&gt; 43</span></div><div class="line">    <span class="keyword">print</span> (x)  <span class="comment"># =&gt; 43</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">set_global_x</span><span class="params">(num)</span>:</span></div><div class="line">    <span class="keyword">global</span> x</div><div class="line">    <span class="keyword">print</span> (x)  <span class="comment"># =&gt; 5</span></div><div class="line">    x = num    <span class="comment"># global var x is now set to 6</span></div><div class="line">    <span class="keyword">print</span> (x)  <span class="comment"># =&gt; 6</span></div><div class="line"></div><div class="line">set_x(<span class="number">43</span>)</div><div class="line">set_global_x(<span class="number">6</span>)</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># Python has first class functions</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">create_adder</span><span class="params">(x)</span>:</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">adder</span><span class="params">(y)</span>:</span></div><div class="line">        <span class="keyword">return</span> x + y</div><div class="line">    <span class="keyword">return</span> adder</div><div class="line"></div><div class="line">add_10 = create_adder(<span class="number">10</span>)</div><div class="line">add_10(<span class="number">3</span>)   <span class="comment"># =&gt; 13</span></div><div class="line"></div><div class="line"><span class="comment"># There are also anonymous functions</span></div><div class="line">(<span class="keyword">lambda</span> x: x &gt; <span class="number">2</span>)(<span class="number">3</span>)                  <span class="comment"># =&gt; True</span></div><div class="line">(<span class="keyword">lambda</span> x, y: x ** <span class="number">2</span> + y ** <span class="number">2</span>)(<span class="number">2</span>, <span class="number">1</span>)  <span class="comment"># =&gt; 5</span></div><div class="line"></div><div class="line"><span class="comment"># There are built-in higher order functions</span></div><div class="line">list(map(add_10, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]))          <span class="comment"># =&gt; [11, 12, 13]</span></div><div class="line">list(map(max, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">2</span>, <span class="number">1</span>]))  <span class="comment"># =&gt; [4, 2, 3]</span></div><div class="line"></div><div class="line">list(filter(<span class="keyword">lambda</span> x: x &gt; <span class="number">5</span>, [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>]))  <span class="comment"># =&gt; [6, 7]</span></div><div class="line"></div><div class="line"><span class="comment"># We can use list comprehensions for nice maps and filters</span></div><div class="line"><span class="comment"># List comprehension stores the output as a list which can itself be a nested list</span></div><div class="line">[add_10(i) <span class="keyword">for</span> i <span class="keyword">in</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]]         <span class="comment"># =&gt; [11, 12, 13]</span></div><div class="line">[x <span class="keyword">for</span> x <span class="keyword">in</span> [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>] <span class="keyword">if</span> x &gt; <span class="number">5</span>]  <span class="comment"># =&gt; [6, 7]</span></div><div class="line"></div><div class="line"><span class="comment"># You can construct set and dict comprehensions as well.</span></div><div class="line">&#123;x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="string">'abcddeef'</span> <span class="keyword">if</span> x <span class="keyword">not</span> <span class="keyword">in</span> <span class="string">'abc'</span>&#125;  <span class="comment"># =&gt; &#123;'d', 'e', 'f'&#125;</span></div><div class="line">&#123;x: x**<span class="number">2</span> <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">5</span>)&#125;  <span class="comment"># =&gt; &#123;0: 0, 1: 1, 2: 4, 3: 9, 4: 16&#125;</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 5. Modules</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># You can import modules</span></div><div class="line"><span class="keyword">import</span> math</div><div class="line">print(math.sqrt(<span class="number">16</span>))  <span class="comment"># =&gt; 4.0</span></div><div class="line"></div><div class="line"><span class="comment"># You can get specific functions from a module</span></div><div class="line"><span class="keyword">from</span> math <span class="keyword">import</span> ceil, floor</div><div class="line">print(ceil(<span class="number">3.7</span>))   <span class="comment"># =&gt; 4.0</span></div><div class="line">print(floor(<span class="number">3.7</span>))  <span class="comment"># =&gt; 3.0</span></div><div class="line"></div><div class="line"><span class="comment"># You can import all functions from a module.</span></div><div class="line"><span class="comment"># Warning: this is not recommended</span></div><div class="line"><span class="keyword">from</span> math <span class="keyword">import</span> *</div><div class="line"></div><div class="line"><span class="comment"># You can shorten module names</span></div><div class="line"><span class="keyword">import</span> math <span class="keyword">as</span> m</div><div class="line">math.sqrt(<span class="number">16</span>) == m.sqrt(<span class="number">16</span>)  <span class="comment"># =&gt; True</span></div><div class="line"></div><div class="line"><span class="comment"># Python modules are just ordinary python files. You</span></div><div class="line"><span class="comment"># can write your own, and import them. The name of the</span></div><div class="line"><span class="comment"># module is the same as the name of the file.</span></div><div class="line"></div><div class="line"><span class="comment"># You can find out which functions and attributes</span></div><div class="line"><span class="comment"># defines a module.</span></div><div class="line"><span class="keyword">import</span> math</div><div class="line">dir(math)</div><div class="line"></div><div class="line"><span class="comment"># If you have a Python script named math.py in the same</span></div><div class="line"><span class="comment"># folder as your current script, the file math.py will</span></div><div class="line"><span class="comment"># be loaded instead of the built-in Python module.</span></div><div class="line"><span class="comment"># This happens because the local folder has priority</span></div><div class="line"><span class="comment"># over Python's built-in libraries.</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 6. Classes</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># We use the "class" operator to get a class</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Human</span>:</span></div><div class="line"></div><div class="line">    <span class="comment"># A class attribute. It is shared by all instances of this class</span></div><div class="line">    species = <span class="string">"H. sapiens"</span></div><div class="line"></div><div class="line">    <span class="comment"># Basic initializer, this is called when this class is instantiated.</span></div><div class="line">    <span class="comment"># Note that the double leading and trailing underscores denote objects</span></div><div class="line">    <span class="comment"># or attributes that are used by python but that live in user-controlled</span></div><div class="line">    <span class="comment"># namespaces. Methods(or objects or attributes) like: __init__, __str__,</span></div><div class="line">    <span class="comment"># __repr__ etc. are called magic methods (or sometimes called dunder methods)</span></div><div class="line">    <span class="comment"># You should not invent such names on your own.</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name)</span>:</span></div><div class="line">        <span class="comment"># Assign the argument to the instance's name attribute</span></div><div class="line">        self.name = name</div><div class="line"></div><div class="line">        <span class="comment"># Initialize property</span></div><div class="line">        self.age = <span class="number">0</span></div><div class="line"></div><div class="line">    <span class="comment"># An instance method. All methods take "self" as the first argument</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, msg)</span>:</span></div><div class="line">        <span class="keyword">print</span> (<span class="string">"&#123;name&#125;: &#123;message&#125;"</span>.format(name=self.name, message=msg))</div><div class="line"></div><div class="line">    <span class="comment"># Another instance method</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">sing</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> <span class="string">'yo... yo... microphone check... one two... one two...'</span></div><div class="line"></div><div class="line">    <span class="comment"># A class method is shared among all instances</span></div><div class="line">    <span class="comment"># They are called with the calling class as the first argument</span></div><div class="line"><span class="meta">    @classmethod</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_species</span><span class="params">(cls)</span>:</span></div><div class="line">        <span class="keyword">return</span> cls.species</div><div class="line"></div><div class="line">    <span class="comment"># A static method is called without a class or instance reference</span></div><div class="line"><span class="meta">    @staticmethod</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">grunt</span><span class="params">()</span>:</span></div><div class="line">        <span class="keyword">return</span> <span class="string">"*grunt*"</span></div><div class="line"></div><div class="line">    <span class="comment"># A property is just like a getter.</span></div><div class="line">    <span class="comment"># It turns the method age() into an read-only attribute</span></div><div class="line">    <span class="comment"># of the same name.</span></div><div class="line"><span class="meta">    @property</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">age</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> self._age</div><div class="line"></div><div class="line">    <span class="comment"># This allows the property to be set</span></div><div class="line"><span class="meta">    @age.setter</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">age</span><span class="params">(self, age)</span>:</span></div><div class="line">        self._age = age</div><div class="line"></div><div class="line">    <span class="comment"># This allows the property to be deleted</span></div><div class="line"><span class="meta">    @age.deleter</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">age</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">del</span> self._age</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># When a Python interpreter reads a source file it executes all its code.</span></div><div class="line"><span class="comment"># This __name__ check makes sure this code block is only executed when this</span></div><div class="line"><span class="comment"># module is the main program.</span></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    <span class="comment"># Instantiate a class</span></div><div class="line">    i = Human(name=<span class="string">"Ian"</span>)</div><div class="line">    i.say(<span class="string">"hi"</span>)                     <span class="comment"># "Ian: hi"</span></div><div class="line">    j = Human(<span class="string">"Joel"</span>)</div><div class="line">    j.say(<span class="string">"hello"</span>)                  <span class="comment"># "Joel: hello"</span></div><div class="line">    <span class="comment"># i and j are instances of type Human, or in other words: they are Human objects</span></div><div class="line"></div><div class="line">    <span class="comment"># Call our class method</span></div><div class="line">    i.say(i.get_species())          <span class="comment"># "Ian: H. sapiens"</span></div><div class="line">    <span class="comment"># Change the shared attribute</span></div><div class="line">    Human.species = <span class="string">"H. neanderthalensis"</span></div><div class="line">    i.say(i.get_species())          <span class="comment"># =&gt; "Ian: H. neanderthalensis"</span></div><div class="line">    j.say(j.get_species())          <span class="comment"># =&gt; "Joel: H. neanderthalensis"</span></div><div class="line"></div><div class="line">    <span class="comment"># Call the static method</span></div><div class="line">    print(Human.grunt())            <span class="comment"># =&gt; "*grunt*"</span></div><div class="line">    print(i.grunt())                <span class="comment"># =&gt; "*grunt*"</span></div><div class="line"></div><div class="line">    <span class="comment"># Update the property for this instance</span></div><div class="line">    i.age = <span class="number">42</span></div><div class="line">    <span class="comment"># Get the property</span></div><div class="line">    i.say(i.age)                    <span class="comment"># =&gt; 42</span></div><div class="line">    j.say(j.age)                    <span class="comment"># =&gt; 0</span></div><div class="line">    <span class="comment"># Delete the property</span></div><div class="line">    <span class="keyword">del</span> i.age</div><div class="line">    <span class="comment"># i.age                         # =&gt; this would raise an AttributeError</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 6.1 Multiple Inheritance</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># Another class definition</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bat</span>:</span></div><div class="line"></div><div class="line">    species = <span class="string">'Baty'</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, can_fly=True)</span>:</span></div><div class="line">        self.fly = can_fly</div><div class="line"></div><div class="line">    <span class="comment"># This class also has a say method</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(self, msg)</span>:</span></div><div class="line">        msg = <span class="string">'... ... ...'</span></div><div class="line">        <span class="keyword">return</span> msg</div><div class="line"></div><div class="line">    <span class="comment"># And its own method as well</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">sonar</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> <span class="string">'))) ... ((('</span></div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    b = Bat()</div><div class="line">    print(b.say(<span class="string">'hello'</span>))</div><div class="line">    print(b.fly)</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># from "filename-without-extension" import "function-or-class"</span></div><div class="line"><span class="keyword">from</span> human <span class="keyword">import</span> Human</div><div class="line"><span class="keyword">from</span> bat <span class="keyword">import</span> Bat</div><div class="line"></div><div class="line"><span class="comment"># Batman inherits from both Human and Bat</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Batman</span><span class="params">(Human, Bat)</span>:</span></div><div class="line"></div><div class="line">    <span class="comment"># Batman has its own value for the species class attribute</span></div><div class="line">    species = <span class="string">'Superhero'</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, *args, **kwargs)</span>:</span></div><div class="line">        <span class="comment"># Typically to inherit attributes you have to call super:</span></div><div class="line">        <span class="comment">#super(Batman, self).__init__(*args, **kwargs)      </span></div><div class="line">        <span class="comment"># However we are dealing with multiple inheritance here, and super()</span></div><div class="line">        <span class="comment"># only works with the next base class in the MRO list.</span></div><div class="line">        <span class="comment"># So instead we explicitly call __init__ for all ancestors.</span></div><div class="line">        <span class="comment"># The use of *args and **kwargs allows for a clean way to pass arguments,</span></div><div class="line">        <span class="comment"># with each parent "peeling a layer of the onion".</span></div><div class="line">        Human.__init__(self, <span class="string">'anonymous'</span>, *args, **kwargs)</div><div class="line">        Bat.__init__(self, *args, can_fly=<span class="keyword">False</span>, **kwargs)</div><div class="line">        <span class="comment"># override the value for the name attribute</span></div><div class="line">        self.name = <span class="string">'Sad Affleck'</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">sing</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> <span class="string">'nan nan nan nan nan batman!'</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    sup = Batman()</div><div class="line"></div><div class="line">    <span class="comment"># Instance type checks</span></div><div class="line">    <span class="keyword">if</span> isinstance(sup, Human):</div><div class="line">        print(<span class="string">'I am human'</span>)</div><div class="line">    <span class="keyword">if</span> isinstance(sup, Bat):</div><div class="line">        print(<span class="string">'I am bat'</span>)</div><div class="line">    <span class="keyword">if</span> type(sup) <span class="keyword">is</span> Batman:</div><div class="line">        print(<span class="string">'I am Batman'</span>)</div><div class="line"></div><div class="line">    <span class="comment"># Get the Method Resolution search Order used by both getattr() and super().</span></div><div class="line">    <span class="comment"># This attribute is dynamic and can be updated</span></div><div class="line">    print(Batman.__mro__)       <span class="comment"># =&gt; (&lt;class '__main__.Batman'&gt;, &lt;class 'human.Human'&gt;, &lt;class 'bat.Bat'&gt;, &lt;class 'object'&gt;)</span></div><div class="line"></div><div class="line">    <span class="comment"># Calls parent method but uses its own class attribute</span></div><div class="line">    print(sup.get_species())    <span class="comment"># =&gt; Superhero</span></div><div class="line"></div><div class="line">    <span class="comment"># Calls overloaded method</span></div><div class="line">    print(sup.sing())           <span class="comment"># =&gt; nan nan nan nan nan batman!</span></div><div class="line"></div><div class="line">    <span class="comment"># Calls method from Human, because inheritance order matters</span></div><div class="line">    sup.say(<span class="string">'I agree'</span>)          <span class="comment"># =&gt; Sad Affleck: I agree</span></div><div class="line"></div><div class="line">    <span class="comment"># Call method that exists only in 2nd ancestor</span></div><div class="line">    print(sup.sonar())          <span class="comment"># =&gt; ))) ... (((</span></div><div class="line"></div><div class="line">    <span class="comment"># Inherited class attribute</span></div><div class="line">    sup.age = <span class="number">100</span></div><div class="line">    print(sup.age)</div><div class="line"></div><div class="line">    <span class="comment"># Inherited attribute from 2nd ancestor whose default value was overridden.</span></div><div class="line">    print(<span class="string">'Can I fly? '</span> + str(sup.fly))</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">####################################################</span></div><div class="line"><span class="comment">## 7. Advanced</span></div><div class="line"><span class="comment">####################################################</span></div><div class="line"></div><div class="line"><span class="comment"># Generators help you make lazy code.</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">double_numbers</span><span class="params">(iterable)</span>:</span></div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> iterable:</div><div class="line">        <span class="keyword">yield</span> i + i</div><div class="line"></div><div class="line"><span class="comment"># Generators are memory-efficient because they only load the data needed to</span></div><div class="line"><span class="comment"># process the next value in the iterable. This allows them to perform</span></div><div class="line"><span class="comment"># operations on otherwise prohibitively large value ranges.</span></div><div class="line"><span class="comment"># <span class="doctag">NOTE:</span> `range` replaces `xrange` in Python 3.</span></div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> double_numbers(range(<span class="number">1</span>, <span class="number">900000000</span>)):  <span class="comment"># `range` is a generator.</span></div><div class="line">    print(i)</div><div class="line">    <span class="keyword">if</span> i &gt;= <span class="number">30</span>:</div><div class="line">        <span class="keyword">break</span></div><div class="line"></div><div class="line"><span class="comment"># Just as you can create a list comprehension, you can create generator</span></div><div class="line"><span class="comment"># comprehensions as well.</span></div><div class="line">values = (-x <span class="keyword">for</span> x <span class="keyword">in</span> [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>])</div><div class="line"><span class="keyword">for</span> x <span class="keyword">in</span> values:</div><div class="line">    print(x)  <span class="comment"># prints -1 -2 -3 -4 -5 to console/terminal</span></div><div class="line"></div><div class="line"><span class="comment"># You can also cast a generator comprehension directly to a list.</span></div><div class="line">values = (-x <span class="keyword">for</span> x <span class="keyword">in</span> [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>])</div><div class="line">gen_to_list = list(values)</div><div class="line">print(gen_to_list)  <span class="comment"># =&gt; [-1, -2, -3, -4, -5]</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># Decorators</span></div><div class="line"><span class="comment"># In this example `beg` wraps `say`. If say_please is True then it</span></div><div class="line"><span class="comment"># will change the returned message.</span></div><div class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> wraps</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">beg</span><span class="params">(target_function)</span>:</span></div><div class="line"><span class="meta">    @wraps(target_function)</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">(*args, **kwargs)</span>:</span></div><div class="line">        msg, say_please = target_function(*args, **kwargs)</div><div class="line">        <span class="keyword">if</span> say_please:</div><div class="line">            <span class="keyword">return</span> <span class="string">"&#123;&#125; &#123;&#125;"</span>.format(msg, <span class="string">"Please! I am poor :("</span>)</div><div class="line">        <span class="keyword">return</span> msg</div><div class="line"></div><div class="line">    <span class="keyword">return</span> wrapper</div><div class="line"></div><div class="line"></div><div class="line"><span class="meta">@beg</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">say</span><span class="params">(say_please=False)</span>:</span></div><div class="line">    msg = <span class="string">"Can you buy me a beer?"</span></div><div class="line">    <span class="keyword">return</span> msg, say_please</div><div class="line"></div><div class="line"></div><div class="line">print(say())                 <span class="comment"># Can you buy me a beer?</span></div><div class="line">print(say(say_please=<span class="keyword">True</span>))  <span class="comment"># Can you buy me a beer? Please! I am poor :(</span></div></pre></td></tr></table></figure>
<h2 id="Ready-For-More"><a href="#Ready-For-More" class="headerlink" title="Ready For More?"></a>Ready For More?</h2><h3 id="Free-Online"><a href="#Free-Online" class="headerlink" title="Free Online"></a>Free Online</h3><ul>
<li><a href="https://automatetheboringstuff.com" target="_blank" rel="external">Automate the Boring Stuff with Python</a></li>
<li><a href="http://pythonpracticeprojects.com" target="_blank" rel="external">Ideas for Python Projects</a></li>
<li><a href="http://docs.python.org/3/" target="_blank" rel="external">The Official Docs</a></li>
<li><a href="http://docs.python-guide.org/en/latest/" target="_blank" rel="external">Hitchhiker’s Guide to Python</a></li>
<li><a href="http://www.python-course.eu/index.php" target="_blank" rel="external">Python Course</a></li>
<li><a href="https://realpython.com/learn/python-first-steps/" target="_blank" rel="external">First Steps With Python</a></li>
<li><a href="https://github.com/vinta/awesome-python" target="_blank" rel="external">A curated list of awesome Python frameworks, libraries and software</a></li>
<li><a href="http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html" target="_blank" rel="external">30 Python Language Features and Tricks You May Not Know About</a></li>
<li><a href="https://www.python.org/dev/peps/pep-0008/" target="_blank" rel="external">Official Style Guide for Python</a></li>
<li><a href="http://cscircles.cemc.uwaterloo.ca/" target="_blank" rel="external">Python 3 Computer Science Circles</a></li>
<li><a href="http://www.diveintopython3.net/index.html" target="_blank" rel="external">Dive Into Python 3</a></li>
<li><a href="http://nbviewer.jupyter.org/gist/anonymous/5924718" target="_blank" rel="external">A Crash Course in Python for Scientists</a></li>
</ul>
<h3 id="Dead-Tree"><a href="#Dead-Tree" class="headerlink" title="Dead Tree"></a>Dead Tree</h3><ul>
<li><a href="http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596158106&amp;linkCode=as2&amp;tag=homebits04-20" target="_blank" rel="external">Programming Python</a></li>
<li><a href="https://www.amazon.com/gp/product/1430224150?ie=UTF8&amp;tag=diveintomark-20&amp;creativeASIN=1430224150" target="_blank" rel="external">Dive Into Python 3</a></li>
<li><a href="https://www.amazon.com/Learn-Python-3-0-VISUALLY-Interactive-ebook/dp/B00YI58B9U/" target="_blank" rel="external">Learn Python 3.0 VISUALLY</a></li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/wechat-reward.JPG" alt="ChangingFond WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/images/alipay-reward.JPG" alt="ChangingFond Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/27/bootstrap-datepicker/" rel="next" title="bootstrap-datepicker插件汉化">
                <i class="fa fa-chevron-left"></i> bootstrap-datepicker插件汉化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/28/import-big-sql/" rel="prev" title="SQL Server导入超大SQL文件的方法">
                SQL Server导入超大SQL文件的方法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "1",
        "bdMiniList": false,
        "bdPic": ""
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      },
      "slide": {
        "bdImg": "5",
        "bdPos": "left",
        "bdTop": "100"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.ico"
               alt="ChangingFond" />
          <p class="site-author-name" itemprop="name">ChangingFond</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/ChangingFond" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/ChangingFond" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://weibo.com/ChangingFond" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Ready-For-More"><span class="nav-number">1.</span> <span class="nav-text">Ready For More?</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Free-Online"><span class="nav-number">1.1.</span> <span class="nav-text">Free Online</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Dead-Tree"><span class="nav-number">1.2.</span> <span class="nav-text">Dead Tree</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ChangingFond</span>
  <span class="author" itemprop="copyrightHolder"></span>
</div>


<div class="powered-by">
  皖ICP备 16015215号
</div>

<div class="theme-info">
  NexT
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"> 访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"> 总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcDoj5z';
      var conf = '4e93ea99e3030a58171f306f452698c3';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  

</body>
</html>
